<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Wechat extends Controller{
	
	public function __construct(){
		parent::__construct();
	}

	/**
	 * 退款回调
	 * @param	
	 */
	public function refundCallback(){
		$xml = file_get_contents('php://input');
		if(isset($xml) && !empty($xml)){
// <xml>
// <return_code>SUCCESS</return_code>
// <appid><![CDATA[wx0b2ec4e132565344]]></appid>
// <mch_id><![CDATA[1724309336]]></mch_id>
// <nonce_str><![CDATA[d167933b539fba3ac1ef6331d175fcc1]]></nonce_str>
// <req_info><![CDATA[5vJgLC\/SYJArzDPLb83IoP6SImqg1RWmXSiqpBu5o5nM\/teUTWCiVQZuxsPIh7+SR1+fDYiss2AYxbNS\/vaUBmdizLymLJgwNiWBieXN\/HXKHT7RCNThY04Ib51J2VN3KBwRSX+BvgQ5RoY8Zzt98Sxn9cc41cuOHF5dugxPC\/nhV5kxaCxXcDi3utwfaS+1LpnYgioY0TFI7MQIi9RkHarC2SefLo6opWXMSCTAxlg4rTkfel8xNB5ObpMl7vEDdpt2mmOYQyZ+GcnjlC4UtyfwIZAKecie0McEZUExAccKkTwC\/EHMNl0G6+4Cog6BP\/TiNr7r5Vs8Zho8QUv6kI3KRbttQA7EDZzDpgmltLd+Sox3ddBvbWVBjEqkMrOLfybhsD\/RGoIJCnINYoDNbaFVs4R18HJHLAEAo5GyNOWAc97d3Wl8SDJkvtXoq6zzG\/IewU4zTM2Uczfs4FFONJOLkhbiB751dta9D44MMrcTGhR4VH5l6javwwCCE6q0NUgMvAcGDMtpNvxRpc0repTlGlbjlGE1XT9tBR5aXIa7j+njWwrYr6WR\/\/x89qduP4VIDALWeCZzNzsGNM82MECcim4mDWq1\/VnBJDnAbVT2KL3qlHE9OtjDlZv+k4HZWfMQZQ3wMMLybBK7wnswdV1iIbad7kMaCUAx2GxmnYdO4erHFIITTHBZcJefBBCpEEpbbQEk\/tG9pCvFixaZ1KMojyBBVsQaN905dDXdiMaEZ5PoV+ZmvD1oOUejZWiM9i22Fjp2d42xYNYypNF+27vZ7x6amQagM+Q5N1BsiLlL7sRd2VlOhyIf+XVLrTHnU65XT2JYL8K+zQmxQdf6NqR+VV5C11UlkSqXgcp9V\/DiUsISOdINvZR0C5zKm3Jkm9URGQxOXSzkvhsW+h+E+LSt0L37QwsJf8q14vY9KOBDKkD0P12Myu3uo1NTFpFRQNroY\/dzkySLYoJh0C0Pf8H0vlLvPAwFFY2\/Ci3QPKZw0Z\/9V7XMZeAJBBYgafw1hiAsPNvCBiioLDXBgUWVGXLfUgETsBJOSHYPdbxKNMiy40xU0+fGHJy7fFu8FCq68GlG2ocXdhRrgaFvG4CN6kSSfJt6IcfjLdnmN0QQ64qGYNTF7oy8OedQVz97B3SP]]></req_info>
// </xml>
// req_info解密后的示例：
// <root>
// <out_refund_no><![CDATA[131811191610442717309]]></out_refund_no>
// <out_trade_no><![CDATA[71106718111915575302817]]></out_trade_no>
// <refund_account><![CDATA[REFUND_SOURCE_RECHARGE_FUNDS]]></refund_account>
// <refund_fee><![CDATA[3960]]></refund_fee>
// <refund_id><![CDATA[50000408942018111907145868882]]></refund_id>
// <refund_recv_accout><![CDATA[支付用户零钱]]></refund_recv_accout>
// <refund_request_source><![CDATA[API]]></refund_request_source>
// <refund_status><![CDATA[SUCCESS]]></refund_status>
// <settlement_refund_fee><![CDATA[3960]]></settlement_refund_fee>
// <settlement_total_fee><![CDATA[3960]]></settlement_total_fee>
// <success_time><![CDATA[2018-11-19 16:24:13]]></success_time>
// <total_fee><![CDATA[3960]]></total_fee>
// <transaction_id><![CDATA[4200000215201811190261405420]]></transaction_id>
// <cash_refund_fee><![CDATA[90]]></cash_refund_fee>
// </root>
			// controller("service/Log") -> logs($xml, 'wechatRefundCallback.txt');
			
			$callbackData = xmlToArray($xml);
			controller("service/Log") -> logs($callbackData, 'wechatRefundCallback.txt');

			$shop = Db::table("gd_shop") -> where(['wechat_pay_mch_id'=>$callbackData['mch_id']]) -> find();

			// 解密req_info
			$req_info_xml = controller("service/Wechat") -> decodeRefundCallback($callbackData['req_info'], $shop['wechat_pay_api_v2']);
			$req_info_arr = xmlToArray($req_info_xml);
			// p($callbackData);
			// p($req_info_arr);die;
			controller("service/Log") -> logs($req_info_xml, 'wechatRefundCallback.txt');

			
			if($callbackData['return_code'] == 'SUCCESS' && $req_info_arr['refund_status'] == 'SUCCESS'){
				$orderWhere[] = ['code', 'eq', $req_info_arr['out_refund_no']];
				$order = Db::table("gd_order") -> where($orderWhere) -> find();

				Db::startTrans();
				if( !empty($order) && $order['status'] != 5 ){
					$saveOrder['status'] = 5;
					$res = Db::table("gd_order") -> where($orderWhere) -> update($saveOrder);
					if( !$res ){
						Db::rollback();
						return false;
					}
				}

				$paymentRecordsWhere[] = ['pay_code', 'eq', $req_info_arr['transaction_id']];
				$paymentRecords = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> find();

				if( !empty($paymentRecords) && $paymentRecords['refund_status'] != 1 ){
					$savePaymentRecords['refund_status'] = 1;
					$savePaymentRecords['refund_price'] = $req_info_arr['refund_fee'] / 100;
					$savePaymentRecords['refund_id'] = $req_info_arr['refund_id'];
					$savePaymentRecords['refund_out_refund_no'] = $req_info_arr['out_refund_no'];
					$savePaymentRecords['refund_desc'] = '';
					$savePaymentRecords['refund_date'] = $req_info_arr['success_time'];
					$savePaymentRecords['refund_type'] = 1;
					$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update($savePaymentRecords);
					if( !$res ){
						Db::rollback();
						return false;
					}
				}
				Db::commit();

				if( $res['code'] == '1' ){
//					给微信返回成功
					echo 'SUCCESS';exit;
				}
			}
		}
	}
	
	/**
	 * 支付回调
	 * @param	orderId：订单ID
	 * @param	identifyId：鉴定ID
	 * @param	auctionId：拍卖ID
	 * @param	auctionSignupId：拍卖报名ID
	 * 
	 * 自定义参数
	 * @param	attach：订单下单拉起支付 = ['payType'=>1, 'orderId'=>orderId, 'out_trade_no'=>'统一下单内部订单号']
	 * @param	attach：我要鉴定拉起支付 = ['payType'=>2, 'identifyId'=>identifyId, 'out_trade_no'=>'统一下单内部订单号']
	 * @param	attach：拍卖报名保证金拉起支付 = ['payType'=>3, 'auctionId'=>auctionId, 'auctionSignupId'=>auctionSignupId, 'out_trade_no'=>'统一下单内部订单号']
	 * @param	attach：拍卖尾款支付拉起支付 = ['payType'=>4, 'auctionId'=>auctionId, 'auctionSignupId'=>auctionSignupId, 'out_trade_no'=>'统一下单内部订单号']
	 * @param	attach：付费咨询下单拉起支付 = ['payType'=>5, 'messageId'=>messageId, 'out_trade_no'=>'统一下单内部订单号']
	 * @param	attach：线下买单拉起支付 = ['payType'=>6, 'orderId'=>orderId, 'out_trade_no'=>'统一下单内部订单号']
	 */
	public function callback(){
		$xml = file_get_contents('php://input');
		if(isset($xml) && !empty($xml)){
//			$xml = '<xml>
//						<appid><![CDATA[wx876691e10b844890]]></appid>
//						<attach><![CDATA[{"userId":27718,"productId":430,"productType":0,"isSkuId":1,"warehouseId":1,"zxDistrictId":18,"refereeId":"27718"}]]></attach>
//						<bank_type><![CDATA[OTHERS]]></bank_type>
//						<cash_fee><![CDATA[1]]></cash_fee>
//						<device_info><![CDATA[wechatMini18]]></device_info>
//						<fee_type><![CDATA[CNY]]></fee_type>
//						<is_subscribe><![CDATA[N]]></is_subscribe>
//						<mch_id><![CDATA[1520429251]]></mch_id>
//						<nonce_str><![CDATA[cdffbc3c2a1c0bcd5f96079fa8daa0b6]]></nonce_str>
//						<openid><![CDATA[oIaHo5az8nNkeA1iHBtQ_fn743g4]]></openid>
//						<out_trade_no><![CDATA[182020101210092532682026]]></out_trade_no>
//						<result_code><![CDATA[SUCCESS]]></result_code>
//						<return_code><![CDATA[SUCCESS]]></return_code>
//						<sign><![CDATA[A52A820015154D5C522BE30E9FD6AA22]]></sign>
//						<time_end><![CDATA[20201012100929]]></time_end>
//						<total_fee>1</total_fee>
//						<trade_type><![CDATA[JSAPI]]></trade_type>
//						<transaction_id><![CDATA[4200000763202010121161184011]]></transaction_id>
//					</xml>';
			
			$callbackData = xmlToArray($xml);
			controller("service/Log") -> logs($callbackData, 'wechatPayCallback.txt');
			
			if($callbackData['result_code'] == 'SUCCESS' && $callbackData['return_code'] == 'SUCCESS'){
				if( isset($callbackData['attach']) && !empty($callbackData['attach']) ) $callbackData['attach'] = json_decode($callbackData['attach'], TRUE);
		
				$type = $callbackData['attach']['payType'];
				switch ($type) {
//					下单
					case '1':
						$res = $this -> editOrder($callbackData);
						break;
//					鉴定
					case '2':
						$res = $this -> editIdentify($callbackData);
						break;
//					拍卖报名保证金
					case '3':
						$res = $this -> editAuction($callbackData);
						break;
//					拍卖尾款
					case '4':
						$res = $this -> editAuction2($callbackData);
						break;
//					付费咨询
					case '5':
						$res = $this -> editMessage($callbackData);
						break;
//					线下买单
					case '6':
						$res = $this -> editOrderShop($callbackData);
						break;
				}
				if( $res['code'] == '1' ){
//					给微信返回成功
					echo 'SUCCESS';exit;
				}
			}
		}
	}
	
	/**
	 * 变更订单
	 */
	private function editOrder($callbackData){
		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$payDate = date("Y-m-d H:i:s", strtotime($callbackData['time_end']));		//支付时间
		$orderId = $callbackData['attach']['orderId'];								//订单ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$transactionId = $callbackData['transaction_id'];							//微信支付订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		
		$where[] = ['id', 'eq', $orderId];
		$oldData = Db::table("gd_order") -> where($where) -> find();
		if( $oldData['status'] != 0 ) return ['code'=>'1'];
		
		Db::startTrans();
		
//		订单
		$save['status'] = 2;
		$save['write_off_status'] = $oldData['goods_type'] == 2 ? '0' : $oldData['write_off_status'];		//水卡，变更待核销状态
		$save['actual_price'] = $totalPrice;
		$save['pay_type'] = $payType;
		$save['pay_code'] = $payCode;
		$save['pay_date'] = $callbackData['time_end'];
		$re = Db::table("gd_order") -> where($where) -> update($save);
		if( !$re ){
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员'];
		}
		
//		订单绑定的鉴定
		$identifyId = 0;
		if( $oldData['is_identify'] == 1 ){
			$oldIdentifyId = Db::table("gd_identify") -> where(['order_id'=>$orderId]) -> find();
			$identifyId = $oldIdentifyId['id'];
			
			$saveIdentify['pay_type'] = $payType;
			$saveIdentify['pay_code'] = $payCode;
			$saveIdentify['pay_date'] = $payDate;
			$saveIdentify['pay_status'] = 1;
			$res = Db::table("gd_identify") -> where(['order_id'=>$orderId]) -> update($saveIdentify);
			if( !$res ) {
				Db::rollback();
				return ['code'=>'-1', 'msg'=>'变更鉴定失败,请联系管理员'];
			}
		}
		
//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$paymentRecordsWhere[] = ['order_id', 'eq', $orderId];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$transactionId]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}
		Db::commit();
		
		return ['code'=>'1'];
	}

	/**
	 * 变更鉴定
	 */
	private function editIdentify($callbackData){
		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$payDate = date("Y-m-d H:i:s", strtotime($callbackData['time_end']));		//支付时间
		$identifyId = $callbackData['attach']['identifyId'];						//鉴定ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$transactionId = $callbackData['transaction_id'];							//微信支付订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		
		$where[] = ['id', 'eq', $identifyId];
		$oldData = Db::table("gd_identify") -> where($where) -> find();
		if( $oldData['pay_status'] != 0 ) return ['code'=>'1'];
		
		Db::startTrans();
		
//		鉴定
		$saveIdentify['pay_type'] = $payType;
		$saveIdentify['pay_code'] = $payCode;
		$saveIdentify['pay_date'] = $payDate;
		$saveIdentify['pay_status'] = 1;
		$res = Db::table("gd_identify") -> where($where) -> update($saveIdentify);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更鉴定失败,请联系管理员'];
		}
		
//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$paymentRecordsWhere[] = ['identify_id', 'eq', $identifyId];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$transactionId]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}
		Db::commit();
		
		return ['code'=>'1'];
	}

	/**
	 * 变更拍卖报名
	 */
	private function editAuction($callbackData){
		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$payDate = date("Y-m-d H:i:s", strtotime($callbackData['time_end']));		//支付时间
		$auctionSignupId = $callbackData['attach']['auctionSignupId'];				//拍卖报名ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		
		$where[] = ['id', 'eq', $auctionSignupId];
		$oldData = Db::table("gd_auction_signup") -> where($where) -> find();
		if( $oldData['status'] != 0 ) return ['code'=>'1'];
		
		Db::startTrans();
		
//		拍卖报名
		$saveIdentify['pay_type'] = $payType;
		$saveIdentify['pay_code'] = $payCode;
		$saveIdentify['pay_date'] = $payDate;
		$saveIdentify['is_bond'] = 1;
		$saveIdentify['status'] = 1;
		$res = Db::table("gd_auction_signup") -> where($where) -> update($saveIdentify);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更拍卖报名失败,请联系管理员'];
		}
		
//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$payCode]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}
		Db::commit();
		
		return ['code'=>'1'];
	}
	
	/**
	 * 变更拍卖尾款
	 */
	private function editAuction2($callbackData){
		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$payDate = date("Y-m-d H:i:s", strtotime($callbackData['time_end']));		//支付时间
		$auctionId = $callbackData['attach']['auctionId'];							//拍卖ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		
		$where[] = ['id', 'eq', $auctionId];
		$oldData = Db::table("gd_auction") -> where($where) -> find();
		if( $oldData['pay_status'] != 0 ) return ['code'=>'1'];
		
		Db::startTrans();
		
//		拍卖报名
		$saveIdentify['pay_type'] = $payType;
		$saveIdentify['pay_code'] = $payCode;
		$saveIdentify['pay_date'] = $payDate;
		$saveIdentify['pay_status'] = 1;
		$res = Db::table("gd_auction") -> where($where) -> update($saveIdentify);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更拍卖失败,请联系管理员'];
		}
		
//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$payCode]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}
		Db::commit();
		
		return ['code'=>'1'];
	}

	/**
	 * 变更付费咨询
	 */
	private function editMessage($callbackData){
		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$payDate = date("Y-m-d H:i:s", strtotime($callbackData['time_end']));		//支付时间
		$messageId = $callbackData['attach']['messageId'];							//咨询ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		
		$where[] = ['id', 'eq', $messageId];
		$oldData = Db::table("gd_message") -> where($where) -> find();
		if( $oldData['pay_status'] != 0 ) return ['code'=>'1'];
		
		Db::startTrans();
		
//		拍卖报名
		$saveIdentify['pay_type'] = $payType;
		$saveIdentify['pay_code'] = $payCode;
		$saveIdentify['pay_date'] = $payDate;
		$saveIdentify['pay_status'] = 1;
		$res = Db::table("gd_message") -> where($where) -> update($saveIdentify);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更咨询失败,请联系管理员'];
		}
		
//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$payCode]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}
		Db::commit();
		
		return ['code'=>'1'];
	}

	/**
	*  线下买单
	* ['payType'=>6, 'orderId'=>orderId, 'out_trade_no'=>'统一下单内部订单号']
	*/
	private function editOrderShop($callbackData){
		$refundOrderNum = 4;								//退款订单数
		$orderId = $callbackData['attach']['orderId'];

		// 订单
		$orderWhere[] = ['id', 'eq', $orderId];
		$order = Db::table("gd_order") -> where($orderWhere) -> find();

		$shop = [];
		if( $order['shop_id'] > 0 ) $shop = Db::table("gd_shop") -> where(['id'=>$order['shop_id']]) -> find();

		// 上级第一单
		$parentOrderWhere[] = ['create_user_id', 'eq', $order['order_user_shop_parent_user_id']];
		$parentOrderWhere[] = ['order_type', 'eq', 9];															//线下买单
		$parentOrderWhere[] = ['status', 'gt', 0];																//非待付款
		$parentOrderWhere[] = ['shop_id', 'eq', $order['shop_id']];
		$parentOrder = Db::table("gd_order") -> where($parentOrderWhere) -> order("id asc") -> find();

		// 上级在该门店的所有有效推荐订单
		$parentOrderWhere2[] = ['order_user_shop_parent_user_id', 'eq', $order['order_user_shop_parent_user_id']];
		$parentOrderWhere2[] = ['order_type', 'eq', 9];
		$parentOrderWhere2[] = ['status', 'gt', 0];
		$parentOrderWhere2[] = ['shop_id', 'eq', $order['shop_id']];
		$parentOrder2 = Db::table("gd_order") -> where($parentOrderWhere2) -> order("id asc") -> select();

		$payType = $callbackData['attach']['payType'];
		$payCode = $callbackData['transaction_id'];									//微信支付订单号
		$totalPrice = $callbackData['total_fee'] / 100;								//实付总金额
		$orderId = $callbackData['attach']['orderId'];								//订单ID
		$outTradeNo = $callbackData['attach']['out_trade_no'];						//统一下单内部订单号
		$transactionId = $callbackData['transaction_id'];							//微信支付订单号
		
		Db::startTrans();

//		订单
		$save['status'] = 1;
		$save['actual_price'] = $totalPrice;
		$save['pay_type'] = $payType;
		$save['pay_code'] = $payCode;
		$save['pay_date'] = $callbackData['time_end'];
		$re = Db::table("gd_order") -> where($orderWhere) -> update($save);
		if( !$re ){
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员'];
		}

//		支付记录
		$paymentRecordsWhere[] = ['out_trade_no', 'eq', $outTradeNo];
		$paymentRecordsWhere[] = ['order_id', 'eq', $orderId];
		$res = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update(['pay_status'=>1, 'pay_code'=>$transactionId]);
		if( !$res ) {
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}

		// 上级第一单未退款
		if( !empty($parentOrder) && !empty($parentOrder2) && $parentOrder['status'] == 1 && count($parentOrder2) >= $refundOrderNum ){
			$c = 0;
			foreach ($parentOrder2 as $k => $v) {
				if( $v['total_price'] >= $parentOrder['total_price'] ) $c = $c+1;
			}
			if( $c >= $refundOrderNum ){

				// 上级第一单的付款数据
				$orderPay = Db::table("gd_payment_records") -> where(['order_id'=>$parentOrder['id']]) -> find();

				// 执行退款
				$weChatConfig['MCH_ID'] = $shop['wechat_pay_mch_id'];
				$weChatConfig['SIGN_TYPE'] = 'MD5';
				$weChatConfig['API_V2'] = $shop['wechat_pay_api_v2'];
				$re = controller("service/Wechat") -> refund($weChatConfig, $orderPay['pay_code'], $parentOrder['total_price'], $parentOrder['total_price'], '消费返还', $parentOrder['code']);
				if( $re['code'] != '1' ){
					Db::rollback();
					return ['code'=>'-1', 'msg'=>'微信执行失败,请联系管理员', 'info'=>$re];
				}

				// 变更订单（上级第一单）
				$saveOrder['status'] = 4;
				$saveOrder['refund_type'] = 1;
				$saveOrder['refund_applyfor_price'] = $parentOrder['total_price'];
				$saveOrder['refund_applyfor_reason'] = '消费返还';
				$saveOrder['refund_applyfor_date'] = date("Y-m-d H:i:s", time());
				$saveOrder['refund_applyfor_status'] = 2;
				$saveOrder['refund_applyfor_status_date'] = date("Y-m-d H:i:s", time());
				$orderRe = Db::table("gd_order") -> where(['id'=>$parentOrder['id']]) -> update($saveOrder);
				if( !$orderRe ){
					Db::rollback();
					return ['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员', 'info'=>$re];
				}

				// 增加返佣记录
				$newReward['create_order_user_id'] = $parentOrder['create_user_id'];
				$newReward['referrer_id'] = $parentOrder['create_user_id'];
				$newReward['type'] = 4;
				$newReward['withdrawal_status'] = '1';
				$newReward['rewards'] = $parentOrder['total_price'];
				$newReward['draw_money'] = $newReward['rewards'];
				$newReward['order_id'] = $parentOrder['id'];
				$newReward['order_code'] = $parentOrder['code'];
				$newReward['create_date'] = date("Y-m-d H:i:s", time());
				$rewardRe = Db::table("gd_reward") -> insertGetId($newReward);
				if( !$rewardRe ){
					Db::rollback();
					return ['code'=>'-1', 'msg'=>'生成记录失败,请联系管理员'];
				}

				// 增加总收益的余额
				$userRe = Db::table("gd_user") -> where(['id'=>$newReward['referrer_id']]) -> setInc('total_income', $newReward['rewards']);
				if( !$userRe ){
					Db::rollback();
					return ['code'=>'-1', 'msg'=>'更新用户失败,请联系管理员'];
				}
			}
		}
		// 上级第一单已退款,走返佣
		if( $parentOrder['status'] == 5 ){

			// 当前订单的付款数据
			$orderPay = Db::table("gd_payment_records") -> where(['order_id'=>$order['id']]) -> find();
			$user = Db::table("gd_user") -> where(['id'=>$order['order_user_shop_parent_user_id']]) -> find();

			// 商店微信支付配置项
			$weChatConfig['MCH_ID'] = $shop['wechat_pay_mch_id'];
			$weChatConfig['SIGN_TYPE'] = 'MD5';
			$weChatConfig['API_V2'] = $shop['wechat_pay_api_v2'];

			// 分账信息
			$receivers = [
				[
					'type'=>'PERSONAL_OPENID',
					'account'=>$user['open_id'],
					'amount'=>$order['total_price'] * 100 * 0.1,
					'description'=>'用户消费',
				],
			];
			// 执行分账（当前订单）
			$re = controller("service/Wechat") -> profitsharing($weChatConfig, $orderPay['pay_code'], $receivers, $order['id']);
			// if( $re['code'] != '1' ){
			// 	Db::rollback();

			// controller("service/log") -> logs($re, 'huidiao.txt');
			// 	return ['code'=>'-1', 'msg'=>'微信执行失败,请联系管理员', 'info'=>$re];
			// }

			// 增加返佣记录
			$newReward['create_order_user_id'] = $order['create_user_id'];
			$newReward['referrer_id'] = $order['order_user_shop_parent_user_id'];
			$newReward['type'] = 3;
			$newReward['withdrawal_status'] = '1';
			$newReward['rewards'] = $order['total_price'] * 0.1;
			$newReward['draw_money'] = $newReward['rewards'];
			$newReward['order_id'] = $order['id'];
			$newReward['order_code'] = $order['code'];
			$newReward['create_date'] = date("Y-m-d H:i:s", time());
			$rewardRe = Db::table("gd_reward") -> insertGetId($newReward);
			if( !$rewardRe ){
				Db::rollback();
				return ['code'=>'-1', 'msg'=>'生成记录失败,请联系管理员'];
			}

			// 增加总收益的余额
			$userRe = Db::table("gd_user") -> where(['id'=>$newReward['referrer_id']]) -> setInc('total_income', $newReward['rewards']);
			if( !$userRe ){
				Db::rollback();
				return ['code'=>'-1', 'msg'=>'更新用户失败,请联系管理员'];
			}
		}

		Db::commit();

		return ['code'=>'1'];
	}

	/**
	*	退款回调
	*/
	private function editOrder2($callbackData){
		// 查支付记录
		$where[] = ['transaction_id', 'eq', $callbackData['pay_code']];
		$paymentRecords = Db::table("gd_payment_records") -> where($where) -> find();

		Db::startTrans();

		// 变更支付记录
		$savePaymentRecordsWhere['refund_status'] = 1;
		$savePaymentRecordsWhere['refund_price'] = $callbackData['req_info']['refund_fee'] / 100;
		$savePaymentRecordsWhere['refund_id'] = $callbackData['req_info']['refund_id'];
		$savePaymentRecordsWhere['refund_out_refund_no'] = $callbackData['req_info']['out_refund_no'];
		$savePaymentRecordsWhere['refund_desc'] = '消费返还';
		$savePaymentRecordsWhere['refund_create_date'] = date("Y-m-d H:i:s", time());
		$savePaymentRecordsWhere['refund_date'] = date("Y-m-d H:i:s", time());
		$savePaymentRecordsWhere['refund_type'] = 1;
		$paymentRecords = Db::table("gd_payment_records") -> where($where) -> update($savePaymentRecordsWhere);
		if( !$paymentRecords ){
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更支付记录失败,请联系管理员'];
		}

		// 变更订单
		$saveOrder['status'] = 5;
		$orderRe = Db::table("gd_order") -> where(['id'=>$paymentRecords['order_id']]) -> update($saveOrder);
		if( !$orderRe ){
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员'];
		}

		Db::commit();

		return ['code'=>'1'];
	}

}

?>